<?php

namespace app\admin\controller\qingdongwms\weixin;

use app\common\controller\Backend;
use addons\qingdongwms\model\StaffDepartment;
use fast\Tree;
use app\admin\model\AuthGroup;
use think\Exception;

/**
 * 部门同步
 *
 */
class Department extends Backend
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new StaffDepartment();
    }

    /**
     * 部门列表
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            // 必须将结果集转换为数组
            $ruleList = collection($this->model->where(array('type' => 1))->order('id', 'desc')->select())->toArray();
            foreach ($ruleList as $k => &$v) {
                $v['name'] = __($v['name']);
            }
            unset($v);
            Tree::instance()->init($ruleList);
            $rulelists = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');

            $ruledata = [0 => __('None')];
            foreach ($rulelists as $k => &$v) {
                $ruledata[$v['id']] = $v['name'];
            }
            $list = $rulelists;
            $total = count($rulelists);

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除部门
     */
    public function del($ids = null)
    {
        if ($this->request->isAjax()) {

            //删除子部门
            $where = ['pid' => array('in', $ids)];
            StaffDepartment::where($where)->delete();

            $map['id'] = array('in', $ids);
            $result = StaffDepartment::where($map)->delete();
            if (!$result) {
                $this->error('删除失败');
            }
            $this->success('删除成功');
        }

        return $this->view->fetch();
    }

    /**
     * 同步到CRM
     */
    public function batch()
    {
        $info = $this->model->where(array('type' => 1, 'status' => 0))->find();
        if (!$info) {
            $this->error('无数据可同步');
        }

        try {
            $result = $this->setDepartment();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('同步成功');
        }
        $this->error('无数据可同步');
    }

    /**
     * 设置部门
     */
    private function setDepartment($pid = 0, $idinfo = 0)
    {
        $list = $this->model->where(array('type' => 1, 'pid' => $pid))->select();
        if (empty($list)) {
            return false;
        }
        foreach ($list as $k => $v) {
            if ($v['status'] != 0) {
                $this->setDepartment($v['id'], $v['role_id']);
                continue;
            }
            $res1 = array(
                'pid' => $idinfo,
                'name' => $v['name'],
                'status' => 'normal',
                'rules' => '*'
            );
            $result1 = AuthGroup::create($res1);
            if (!$result1) {
                throw new Exception('同步失败');
            }
            $idinfo = AuthGroup::getLastInsID();
            $pid = $v['id'];
            $this->setDepartment($pid, $idinfo);
            $this->model->where(array('id' => $v['id']))->update(array('status' => 1, 'role_id' => $idinfo));
        }
        return true;
    }

}